﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WLYT.Domain.Model;

namespace WLYT.Common
{
    public class WebUtils
    {
        private static readonly ILog loginfo = LogManager.GetLogger("loginfo");

        public static string HttpGet(string url, Encoding encode = null)
        {
            string result;

            try
            {
                var webClient = new WebClient { Encoding = Encoding.UTF8 };

                if (encode != null)
                    webClient.Encoding = encode;

                result = webClient.DownloadString(url);
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            return result;
        }

        public static string HttpPost(string url, object obj)
        {
            long startTime = DateTime.Now.Ticks;
            string requestContent = JsonConvert.SerializeObject(obj);
            byte[] bs = Encoding.UTF8.GetBytes(requestContent);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json;charset=UTF-8";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                StreamReader streamReader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
                string result = streamReader.ReadToEnd();
                loginfo.Info(new LogRecord { Method = req.Method, RequestUri = url, RequestContent = requestContent, ResponseContent = result, Timer =  (int)((DateTime.Now.Ticks - startTime) / 10000) });
                return result;
            }
        }

        public static T HttpGet<T>(string url, Encoding encode = null)
        {
            var res = HttpGet(url, encode);
            return JsonConvert.DeserializeObject<T>(res);
        }

        public static T HttpPost<T>(string url, object obj)
        {
            var res = HttpPost(url, obj);
            return JsonConvert.DeserializeObject<T>(res);
        }

        public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            using (HttpClient client = new HttpClient())
            {
                if (contentType != null)
                    client.DefaultRequestHeaders.Add("ContentType", contentType);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }

        public static async Task<string> HttpPostAsync(string url, object postData = null, string contentType = "application/json", int timeOut = 10, Dictionary<string, string> headers = null)
        {
            long startTime = DateTime.Now.Ticks;
            string requestContent = JsonConvert.SerializeObject(postData ?? "");

            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(requestContent, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    string result = await response.Content.ReadAsStringAsync();
                    loginfo.Info(new LogRecord { Method = "POST", RequestUri = url, RequestContent = requestContent, ResponseContent = result, Timer =  (int)((DateTime.Now.Ticks - startTime) / 10000) });
                    return result;
                }
            }
        }

        public static async Task<T> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
        {
            var res = await HttpGetAsync(url, contentType, headers);
            return JsonConvert.DeserializeObject<T>(res);
        }

        public static async Task<T> HttpPostAsync<T>(string url, object postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
        {
            var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
            return JsonConvert.DeserializeObject<T>(res);
        }
    }
}